package org.example.common;

import lombok.Getter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@Component
@Getter
public class RouteCacheManage {
    @Resource
    private RoutingCacheMapper routingCacheMapper;
    private static List<RoutingCache> routingCaches = new CopyOnWriteArrayList<>();

    public List<RoutingCache> getRoutingCaches() {
        if (routingCaches.isEmpty()) {
            synchronized (RouteCacheManage.class) {
                if (routingCaches.isEmpty()) {
                    routingCaches = routingCacheMapper.getAll();
                }
            }
        }
        return routingCaches;
    }

    public List<String> findTargetTbl(String shardVal,
                                      String shardCol) {

        if (routingCaches.isEmpty()) {
            getRoutingCaches();
        }
        return routingCaches.stream().filter(routingCache->routingCache.getShardCol().equals(shardCol) &&
                routingCache.getShardVal().equals(shardVal))
                .map(RoutingCache::getTargetTbl)
                .collect(Collectors.toList());
    }
}
